import React, { Component } from 'react';
import _ from 'lodash';
import {
  StyleSheet, View, Text, TouchableOpacity, Modal, FlatList, Alert, DeviceEventEmitter,
} from 'react-native';
import produce from 'immer';
import { Icon } from 'native-base';
import {
  ListFooter, BlankBackground, Loading,
} from './index';
import * as todoService from '../services/todo';
import MySearchBar from './searchbar';
import AddKeyword from './add-keyword';
import theme from '../native-base-theme/variables';
import MyHeader from './header';
import { UtilToast } from '../utils/util-method';

export default class FormSearchKeyword extends Component {
  page = 1; // 分页请求的当前页数

  startPosition = 0; // 开始滑动的位置

  index = 0; // 记录当前page的index

  searchValue = '';

  constructor(props) {
    super(props);
    this.state = {
      list: [],
      refreshing: false,
      isMore: false,
      isError: false,
      showLoading: true,
    };
  }

  componentDidMount() {
    this._onInitRefresh();
  }

  fetchList = async (payload) => {
    try {
      this.setState({ isError: false });
      const currPage = this.page + 1;
      const { list, page, total } = await todoService.choiceKeywordSearch({ ...payload, page: currPage }, this.props.searchUri);

      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list.push(...list);
        this.page = page;
        draft.isMore = draft.list.length < total;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true });
    }
  }

  refreshList = async (payload) => {
    try {
      this.setState({ isError: false });
      const { list, page, total } = await todoService.choiceKeywordSearch({ ...payload, page: 1 }, this.props.searchUri);
      const isMore = list.length < total;
      this.setState(produce(draft => {
        // eslint-disable-next-line no-restricted-syntax
        draft.list = list;
        draft.refreshing = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true, refreshing: false });
    }
  }

  initRefreshList = async (payload) => {
    try {
      this.setState({ showLoading: true, isError: false, list: [] });
      const { list, page, total } = await todoService.choiceKeywordSearch({ ...payload, page: 1 }, this.props.searchUri);
      const isMore = list.length < total;
      this.setState(produce(draft => {
        draft.list = list;
        draft.showLoading = false;
        this.page = page;
        draft.isMore = isMore;
        draft.total = total;
      }));
    } catch (error) {
      this.setState({ isError: true, showLoading: false });
    }
  }

  // 刷新时候获取数据
  _onRefresh = () => {
    if (this.props.extraInfo) {
      this.refreshList({ condition: this.searchValue, ...this.props.extraInfo });
    } else {
      this.refreshList({ condition: this.searchValue });
    }
  }

  // 初始化的时候获取数据
  _onInitRefresh = () => {
    if (this.props.extraInfo) {
      this.initRefreshList({ condition: this.searchValue, ...this.props.extraInfo });
    } else {
      this.initRefreshList({ condition: this.searchValue });
    }
  }

  // 上拉加载数据
  _onEndReached = () => {
    if (this.state.isMore) {
      if (this.props.extraInfo) {
        this.fetchList({ condition: this.searchValue, ...this.props.extraInfo });
      } else {
        this.fetchList({ condition: this.searchValue });
      }
    }
  }

  _onItemClick = (item) => {
    // let list = [];
    // if (this.props.type === 'radio') { // 单选
    //   list = this.state.list.map((it, index) => ({
    //     ...it,
    //     checked: index === item.index,
    //   }));
    //   this.setState(produce(draft => {
    //     draft.list = list;
    //   }));
    // } else { // 多选
    //   this.setState(produce(draft => {
    //     draft.list[item.index].checked = !draft.list[item.index].checked;
    //   }));
    // }
    this.props.choiceConfirm([{ id: item.item.id, name: item.item.name }]);
    this.props.onClose();
  }

  // 列表的item组件
  _renderItem = (item) => (
    <TouchableOpacity
      style={{ padding: 10, justifyContent: 'space-between', flexDirection: 'row', backgroundColor: item.item.checked ? '#207aff' : theme.myPrimary }}
      onPress={() => this._onItemClick(item)}
    >
      <Text style={{ color: 'white', marginTop: 5, marginBottom: 5 }}>
        {item.item.name} {item.item.times && (`（${item.item.times}）`)}
      </Text>
    </TouchableOpacity>
  );

  // 列表的分割线
  _renderItemSeparator = () => (
    <View style={{ height: 1, backgroundColor: '#EDF5FA' }} />
  )

  // 列表上拉加载的组件
  _renderListFooter = () => (
    (this.state.list.length > 0) && <ListFooter isMore={this.state.isMore} />
  );

  _onSearch = async (searchValue) => {
    this.searchValue = searchValue;
    if (this.props.extraInfo) {
      this.initRefreshList({ condition: this.searchValue, ...this.props.extraInfo });
    } else {
      this.initRefreshList({ condition: this.searchValue });
    }
  }

  _addKeyword = async (keyword) => {
    // this.searchValue = searchValue;
    // this.initRefreshList({ condition: this.searchValue });
    Alert.alert(
      '提示',
      '确定新增吗？',
      [
        {
          text: '取消',
          style: 'cancel',
          onPress: () => {
          },
        },
        {
          text: '确定',
          onPress: () => {
            this.addkeyWordConfirm(keyword);
          },
        },
      ],
    );
  }

  getDatas = async (keyword) => {
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const data = await todoService.addKeyword({ ...this.props.extraAddkeywordInfo }, keyword, this.props.searchUri);
      // const data = await techDocService.getTechPerformance({ objType: 'RX_240ZLJZKGZZ' });
      DeviceEventEmitter.emit('showLoading', false);
      if (data && data.id) {
        this.props.choiceConfirm([{ id: data.id, name: data.name }]);
        this.props.onClose();
      } else {
        // UtilToast('添加失败！', 'danger');
        // alert('添加失败！');
        Alert.alert(
          '提示',
          '添加失败',
          [
            { text: '取消', style: 'cancel' },
            {
              text: '确定',
            },
          ],
        );
      }
    } catch (e) {
      console.log(e);
      DeviceEventEmitter.emit('showLoading', false);
      Alert.alert(
        '提示',
        e.name,
        [
          { text: '取消', style: 'cancel' },
          {
            text: '确定',
          },
        ],
      );
      // alert('该关键字已经存在！');
    }
  }

  addkeyWordConfirm = (keyword) => {
    // const list = this.state.list.filter((it) => (it.checked));
    if (keyword) {
      // this.props.choiceConfirm([{ id: '001', name: keyword }]);
      // this.props.onClose();
      this.getDatas(keyword);
    } else {
      // UtilToast('keyword', 'danger');
      // alert('请输入关键字');
      Alert.alert(
        '提示',
        '请输入新增内容！',
        [
          { text: '取消', style: 'cancel' },
          {
            text: '确定',
          },
        ],
      );
    }
  };

  render() {
    const {
      onClose, modalVisible,
    } = this.props;

    const {
      showLoading, isError, list, refreshing,
    } = this.state;

    let mView = <Loading />;
    if (!showLoading) {
      if (list.length === 0) {
        mView = <BlankBackground isError={isError} onRefresh={this._onInitRefresh} />;
      } else {
        mView = (
          <FlatList
            renderItem={this._renderItem}
            data={list}
            keyExtractor={(item, index) => item + index}
            onRefresh={this._onRefresh}
            refreshing={refreshing}
            onEndReachedThreshold={0.05}
            onEndReached={this._onEndReached}
            ListFooterComponent={this._renderListFooter}
            ItemSeparatorComponent={this._renderItemSeparator}
          />
        );
      }
    }

    // const header = !this.props.searchNoHeader ? (
    //   <View>
    //     <MySearchBar placeholder="请输入搜索内容" cancel={onClose} search={this._onSearch} />
    //   </View>
    // ) : (
    //   <View>
    //     <MyHeader cancel={onClose} title={this.props.title} confirm={this.choiceConfirm} />
    //   </View>
    // );

    const header = (
      <View>
        <MySearchBar placeholder={this.props.searchPlaceholder} cancel={onClose} search={this._onSearch} />
      </View>
    );

    return (
      <Modal
        visible={modalVisible}
        animationType="none"
        transparent={false}
        onRequestClose={onClose}
        style={styles.modalConteniner}
      >
        {header}
        <View style={{ flex: 1, backgroundColor: theme.myPrimary }}>
          {mView}
        </View>
        <View style={styles.footer}>
          <AddKeyword placeholder={this.props.searchPlaceholder} search={this._addKeyword} />
        </View>
        {/* {!this.props.searchNoHeader && (
          <TouchableOpacity style={styles.footer} onPress={this.choiceConfirm} activeOpacity={0.8}>
            <Text style={{ color: 'white' }}>确定</Text>
          </TouchableOpacity>
        )} */}
      </Modal>
    );
  }
}

const styles = StyleSheet.create({
  modalConteniner: {
    flex: 1,
    height: 200,

  },
  record_text: {
    paddingLeft: 10,
    paddingBottom: 10,
    fontSize: 12,
  },
  record_text_container: {
    padding: 10,
    flex: 1,
  },
  record_text_bg: {
    padding: 12,
    borderTopWidth: 1,
    borderTopColor: '#DEE1E6',
    backgroundColor: '#fff',
  },
  clear_text_bg: {
    padding: 12,
    borderTopWidth: 1,
    borderTopColor: '#DEE1E6',
    textAlign: 'center',
    fontSize: 12,
  },
  footer: {
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: theme.myPrimary,
    height: 48,
  },
});
